<script lang="ts">
    import { get_unread_count } from "$lib/api/board/board_chat";
    import {
        DRAW_ORDER_BY_CHAT,
        list_draw,
        type DrawInfo,
    } from "$lib/api/board/board_draw";
    import { boardStore } from "$lib/stores/board.svelte";
    import { userStore } from "$lib/stores/user.svelte";
    import { request } from "$lib/utils/request";
    import { listen } from "@tauri-apps/api/event";
    import type { AllNotice } from "$lib/api/notice_type";
    import dayjs from "dayjs";
    import { openBoardDrawWindow } from "$lib/utils/window";

    type ExDrawInfo = DrawInfo & {
        unReadCount?: number;
    };

    const PAGE_SIZE = 10;
    let drawList = $state([] as ExDrawInfo[]);
    let drawVersion = $state(0);

    async function loadDrawList(drawId?: string) {
        const tmpMap: Map<string, number> = new Map();
        for (const draw of drawList) {
            if (draw.unReadCount != undefined) {
                tmpMap.set(draw.draw_id, draw.unReadCount);
            }
        }
        const res = await request(
            list_draw({
                session_id: userStore.userSession,
                board_id: boardStore.curBoardId,
                order_by: DRAW_ORDER_BY_CHAT,
                offset: 0,
                limit: PAGE_SIZE,
            }),
        );
        const tmpList: ExDrawInfo[] = [];
        for (const draw of res.draw_list) {
            let unReadCount = tmpMap.get(draw.draw_id);
            if (unReadCount == undefined || drawId == draw.draw_id) {
                const readStateRes = await request(
                    get_unread_count({
                        session_id: userStore.userSession,
                        board_id: boardStore.curBoardId,
                        draw_id: draw.draw_id,
                    }),
                );
                unReadCount = readStateRes.unread_count;
            }
            tmpList.push({
                ...draw,
                unReadCount: unReadCount,
            });
        }
        //检查是否变更,防止出现循环

        if (tmpList.length > 0 && drawList.length > 0) {
            if (
                tmpList[0].last_chat_time == drawList[0].last_chat_time &&
                tmpList[0].unReadCount == drawList[0].unReadCount
            ) {
                return;
            }
        }
        if (tmpList.length == drawList.length) {
            let changeCount = 0;
            tmpList.forEach((item,i)=>{
                if(item.board_id != drawList[i].board_id){
                    changeCount++;
                }
                if(item.last_chat_time != drawList[i].last_chat_time){
                    changeCount++;
                }
                if(item.unReadCount != drawList[i].unReadCount){
                    changeCount++;
                }
                if(item.update_time != drawList[i].update_time){
                    changeCount++;
                }
            })
            if (changeCount == 0) {
                return;
            }
        }

        drawList = tmpList;
    }

    $effect(() => {
        if (
            userStore.userSession != "" &&
            boardStore.drawVersion == drawVersion
        ) {
            loadDrawList();
        }
    });

    $effect(() => {
        if (
            userStore.userSession != "" &&
            boardStore.drawVersion != drawVersion
        ) {
            drawVersion = boardStore.drawVersion;
            loadDrawList();
        }
    });

    $effect(() => {
        const unListen = listen<AllNotice>("notice", (ev) => {
            const payload = ev.payload;
            if (payload.BoardNotice != undefined) {
                if (
                    payload.BoardNotice.NewChatMsgNotice?.board_id ==
                        boardStore.curBoardId &&
                    payload.BoardNotice.NewChatMsgNotice?.draw_id != ""
                ) {
                    loadDrawList(payload.BoardNotice.NewChatMsgNotice?.draw_id);
                } else if (
                    payload.BoardNotice.UpdateDrawNotice?.board_id ==
                    boardStore.curBoardId
                ) {
                    if (
                        drawList
                            .map((item) => item.draw_id)
                            .includes(
                                payload.BoardNotice.UpdateDrawNotice.draw_id,
                            )
                    ) {
                        loadDrawList();
                    }
                } else if (
                    payload.BoardNotice.RemoveDrawNotice?.board_id ==
                    boardStore.curBoardId
                ) {
                    if (
                        drawList
                            .map((item) => item.draw_id)
                            .includes(
                                payload.BoardNotice.RemoveDrawNotice.draw_id,
                            )
                    ) {
                        loadDrawList();
                    }
                }
            } else if (payload.ClientNotice != undefined) {
                if (
                    payload.ClientNotice.ClearDrawMsgReadStateNotice
                        ?.board_id == boardStore.curBoardId
                ) {
                    if (
                        drawList
                            .map((item) => item.draw_id)
                            .includes(
                                payload.ClientNotice.ClearDrawMsgReadStateNotice
                                    .draw_id,
                            )
                    ) {
                        loadDrawList(
                            payload.ClientNotice.ClearDrawMsgReadStateNotice
                                .draw_id,
                        );
                    }
                }
            }
        });
        return () => {
            unListen.then((fn) => fn());
        };
    });
</script>

<div class="w-[200px] border-l-1 border-surface-200-800">
    <header
        class="h-[50px] bg-surface-200-800 p-1 flex items-center justify-center"
    >
        <h6 class="h6">最近沟通话题</h6>
    </header>
    <main class="h-[calc(100vh-160px)] overflow-y-auto">
        <ul>
            {#each drawList as draw}
                <li class="m-1 bg-surface-200-800 p-1 rounded-[10px]">
                    <div class="relative">
                        {#if (draw.unReadCount ?? 0) > 0}
                            <span
                                class="badge-icon preset-filled-primary-500 absolute -right-0 -top-0 z-10"
                                >{draw.unReadCount ?? 0}</span
                            >
                        {/if}
                        <button
                            type="button"
                            class="h6 text-wrap break-all pl-1"
                            onclick={() =>
                                openBoardDrawWindow(
                                    boardStore.curBoardId,
                                    draw.draw_id,
                                )}
                        >
                            话题:{draw.basic_info.draw_name}
                        </button>
                        <div class="flex justify-end">
                            {dayjs(draw.last_chat_time).format(
                                "YYYY-MM-DD HH:mm:ss",
                            )}
                        </div>
                    </div>
                </li>
            {/each}
        </ul>
    </main>
</div>
